package com.aw.baselib.widgets

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.widget.TextView

/**
 * @author : hzw
 * @date : 2021/12/9
 * https://blog.csdn.net/JingleYe/article/details/51773290
 */
@SuppressLint("AppCompatCustomView")
internal class DrawableCenterTextView : TextView {
    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    )

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?) : super(context)

    override fun onDraw(canvas: Canvas) {
        val drawables = compoundDrawables
        if (drawables != null) {
            val drawableTop = drawables[1]
            for (i in drawables.indices) {
                val drawable = drawables[i]
                if (drawable != null) {
                    if (i == 0 || i == 3) {
                        //drawableLeft or drawableRight with singline text four word ()
                        //                        float textWidth = getPaint().measureText(getText().toString());
                        val textWidth = paint.measureText("正正正正")
                        val drawablePadding = compoundDrawablePadding
                        var drawableWidth = 0
                        drawableWidth = drawable.intrinsicWidth
                        val bodyWidth = textWidth + drawableWidth + drawablePadding
                        canvas.translate((width - bodyWidth) / 2, 0f)
                    } else if (i == 1 || i == 4) {
                        //drawableTop or drawableBottom
                        val textHeight = paint.measureText("正")
                        val drawablePadding = compoundDrawablePadding
                        val drawableHeight = drawableTop.intrinsicHeight
                        val bodyWidth = textHeight + drawableHeight + drawablePadding
                        canvas.translate(0f, (height - bodyWidth) / 2)
                    }
                }
            }
        }
        super.onDraw(canvas)
    }
}